<template>
  <div class="employees-container">
    <div class="app-container">
      <PageTools>
        <template #left>
          <span>总记录数: {{ total }} 条</span>
        </template>
        <template #right>
          <el-button type="warning" size="small" @click="$router.push('/import')">excel导入</el-button>
          <el-button type="danger" size="small" @click="exportExcel">excel导出</el-button>
          <el-button type="primary" size="small" @click="showDialog=true">新增员工</el-button>
        </template>
      </PageTools>

      <el-card style="margin-top: 10px;">
        <el-table
          border
          :data="list"
          :default-sort="{prop: 'timeOfEntry', order: 'descending'}"
        >
          <el-table-column label="序号" type="index" />
          <el-table-column label="姓名" prop="username" />
          <el-table-column label="员工头像" prop="username">
            <template #default="{row}">
              <img
                v-imgerror="require('@/assets/common/bigUserHeader.png')"
                src="row.staffPhoto"
                alt=""
                style="width:50%"
                @click="showCode(row.staffPhoto)"
              >
            </template>
          </el-table-column>
          <el-table-column label="工号" prop="workNumber" />
          <el-table-column label="聘用形式" prop="formOfEmployment">
            <template #default="{row}">
              {{ formatEmployment(row.formOfEmployment) }}
            </template>
          </el-table-column>
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column label="入职时间" prop="timeOfEntry" sortable />
          <!-- <el-table-column label="账户状态" /> -->
          <el-table-column label="操作" width="280">
            <template #default="{row}">
              <el-button type="text" size="small" @click="$router.push(`/employees/detail/${row.id}`)">查看</el-button>
              <el-button type="text" size="small">分配角色</el-button>
              <el-button type="text" size="small" @click="hDel(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <el-pagination
            layout="prev, pager, next"
            :page-size="size"
            :total="total"
            :current-page.sync="page"
            @current-change="handleCurrentChange"
          />
        </el-row>
      </el-card>
      <el-dialog title="新增员工" :visible.sync="showDialog">
        <EmpDialog @success="hSuccess" />
      </el-dialog>
      <el-dialog title="生成二维码图片" :visible.sync="showCodeDialog">
        <el-row type="flex" justify="center">
          <!-- 画布是用来显示二维码图片  -->
          <canvas ref="myCanvas" />

        </el-row>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { getEmployee, delEmployee } from '@/api/employees'
import EmployeeEnum from '@/constant/employees'
import EmpDialog from './empDialog.vue'
import QRCode from 'qrcode'
console.log(EmployeeEnum, '对象')
// 将{id:1,value:正式,},  {id: 1, value: '正式' } 装换成{1:正式，2：非正式}
const hireType = EmployeeEnum.hireType.reduce((acc, item) => {
  acc[item.id] = item.value
  return acc
}, {})
// console.log(hireType)
export default {
  components: {
    EmpDialog
  },
  data() {
    return {
      showCodeDialog: false,
      list: [],
      page: 1,
      size: 5,
      total: 0,
      showDialog: false
    }
  },
  created() {
    this.loadgetEmployee()
  },
  methods: {
    showCode(url) {
      if (url) {
        this.showCodeDialog = true // dom更新是异步的
        // 生成二维码图片
        this.$nextTick(() => {
          const canvas = this.$refs.myCanvas
          // 生成二维码图片
          QRCode.toCanvas(canvas, url)
        })
      } else {
        this.$message.error('请传入正确的图片')
      }
    },
    // 核心实现导出的代码
    exportExcel() {
      const { tHeader, data } = this.transZhKeyToExcel(this.list)
      // import('@/vendor/Export2Excel')  懒加载的方式导入一个模块， 返回值是一个promise实例
      import('@/vendor/Export2Excel').then(excel => {
        // excel指的模块对象，那么就可以使用这个模块对象去调用这个模块里面的函数或者访问变量   excel.函数名()

        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: this.filename,
          autoWidth: this.autoWidth,
          bookType: this.bookType
        })
        this.downloadLoading = false
      })
    },
    transZhKeyToExcel(list) {
      // 中引文的映射对象
      const mapInfo = {
        'id': '编号',
        'password': '密码',
        'mobile': '手机号',
        'username': '姓名',
        'timeOfEntry': '入职日期',
        'formOfEmployment': '聘用形式',
        'correctionTime': '转正日期',
        'workNumber': '工号',
        'departmentName': '部门',
        'staffPhoto': '头像地址'
      }
      // 1.生成表头
      const one = list[0]
      if (!one) return
      const tHeader = Object.keys(one).map(enkey => {
        return mapInfo[enkey]
      })
      // 2.生成表的内容 data
      const data = list.map(item => {
        return Object.values(item)
      })
      return { tHeader, data }
    },
    hDel(id) {
      this.$confirm('此操作将永久删除部门, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        const res = await delEmployee(id)
        if (res.code === 10000) {
          this.$message.success(res.message)
          if (this.list.length === 1) {
            this.page--
            if (this.page <= 0) {
              this.page = 1
            }
          }
          this.loadgetEmployee()
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '取消删除'
        })
      })
    },
    hSuccess() {
      this.total++
      // 求最大页码值    总条数除每页的条数
      const maxPage = Math.ceil(this.total / this.size)
      // 改变当前的页码值
      this.page = maxPage
      this.showDialog = false
      this.loadgetEmployee()
    },
    // 当前页码值切换时触发
    handleCurrentChange(val) {
      this.page = val
      this.loadgetEmployee()
    },
    // 格式化数据的函数
    formatEmployment(id) {
      return hireType[id] || '未知'
    },
    async loadgetEmployee() {
      try {
        const res = await getEmployee({ page: this.page, size: this.size })
        console.log(res, '获取员工列表')
        this.list = res.data.rows
        this.total = res.data.total
      } catch (error) {
        this.$message.error(error)
      }
    }
  }
}
</script>
